import org.json.JSONObject;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

// 查询订单，发送POST请求
public class Orders {

    /**
     * 获取由订单信息生成的JSON字符串
     * @return
     * @throws Exception
     */
    public void getOrderJson() throws Exception {
        // 连接数据库
        Connection conn =  ConnectDB.getConnection();

        // sql语句
        String queryOrderSql = "select id, remark from saleorder";
        String queryOrderLineSql = "select material, qty from saleorderline where orderId =";

        // 获取执行sql的对象Statement
        Statement orderStmt = conn.createStatement();
        Statement orderLineStmt = conn.createStatement();

        // 获取订单表头信息
        ResultSet orderRes = orderStmt.executeQuery(queryOrderSql);

        // 处理结果，生成JSON
        JSONObject orderJson = new JSONObject();
        while(orderRes.next()){
            // 存放表头信息
            Map orderMap = new HashMap();
            orderMap.put("state", 0);
            orderMap.put("remark", orderRes.getString(2));
            orderMap.put("template", "料箱入库");

            // 获取订单行信息
            String orderId = orderRes.getString(1);
            ResultSet orderLineRes = orderLineStmt.executeQuery(queryOrderLineSql+orderId);
            // 存放订单行信息
            Vector<Map<String, String>> orderLineVec = new Vector<>();
            while(orderLineRes.next()){
                Map orderLineMap = new HashMap();
                orderLineMap.put("part", orderLineRes.getString(1));
                orderLineMap.put("expectedQty", null);
                orderLineMap.put("actualQty", orderLineRes.getInt(2));
                orderLineMap.put("lotNo", null);
                orderLineVec.add(orderLineMap);
            }
            orderLineRes.close();
            // 生成JSON字符串
            orderJson.put("order", orderMap);
            orderJson.put("lines", orderLineVec);
            // 发送POST请求
            String httpRes = HttpClientUtils.sendHttpPost("http://localhost:8880/api/inbound/create", orderJson);
            // 处理结果...


        }
        orderRes.close();

        // 释放资源
        orderLineStmt.close();
        orderStmt.close();
        conn.close();
    }
}
